package org.example.controller;

import org.example.config.JwtUtil;
import org.example.entity.Account;
import org.example.entity.Authority;
import org.example.entity.ResultMap;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("jwt")
public class JwtTestController {

    @Autowired
    AccountService accountService;

    @PostMapping("/login")
    public ResultMap<Account> Login(@RequestBody Account account) {
        ResultMap<Account> resultMap = new ResultMap<>();
        //通过用户名拿到用户实体类
        Account result = accountService.loginByUserName(account.getUsername());
        //然后进行密码的加密后的比较
        boolean b = JwtUtil.matchsPassword(account.getPassword(), result.getPassword());
        //如果密码一致表示登录成功
        if (result != null && b) {
            List<Authority> author = accountService.getAccountAuthority(account.getUsername());
            resultMap.setCode(200L);
            resultMap.setMessage("登录成功");
            resultMap.setResult(result);
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), result, author.get(0).getAuthority(), 3600L * 1000);
            resultMap.setToken(token);
        } else {
            resultMap.setCode(-1);
            resultMap.setMessage("登录失败");
        }
        return resultMap;
    }

    @RequestMapping("/vip/queryAllUser")
    public ResultMap<List<Account>> queryAllUser() {
        ResultMap<List<Account>> resultMap = new ResultMap<>();
        List<Account> accounts = accountService.queryAllUser();
        //如果密码一致表示登录成功
        if (accounts != null) {

            resultMap.setCode(200L);
            resultMap.setMessage("查询成功");
            resultMap.setResult(accounts);
           // String token = JwtUtil.createJWT(UUID.randomUUID().toString(), result, author.get(0).getAuthority(), 3600L * 1000);
          //  resultMap.setToken(token);
        } else {
            resultMap.setCode(-1);
            resultMap.setMessage("查询失败");
        }
        return resultMap;
    }


    @RequestMapping("/register")
    public ResultMap<Integer> register(@RequestBody Account account) {
        ResultMap<Integer> resultMap = new ResultMap<>();
        account.setId(0);
        account.setPassword(JwtUtil.encoderPassword(account.getPassword()));
        int register = accountService.register(account);
        if (register > 0) {
            resultMap.setCode(200);
            resultMap.setResult(1);
        } else {
            resultMap.setCode(-1);
            resultMap.setResult(0);
        }
        return resultMap;
    }

    @RequestMapping("/vip/test")
    public String test() {
        return "test";
    }

    @RequestMapping("/test")
    public String test2() {
        return "test2";
    }
}
